/**
 * Agent Thinking Process Component
 * 
 * Displays the agent's reasoning steps and sub-agent invocations
 */

import { Brain, Cpu, Zap, ChevronRight } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import type { SubAgentExecution } from '@/lib/sidecar-runtime';

interface AgentThinkingProcessProps {
  executions: SubAgentExecution[];
  showOnlyActive?: boolean;
}

export function AgentThinkingProcess({
  executions,
  showOnlyActive = false,
}: AgentThinkingProcessProps) {
  const displayExecutions = showOnlyActive
    ? executions.filter((e) => e.status === 'pending' || e.status === 'running')
    : executions;

  if (displayExecutions.length === 0) {
    return null;
  }

  const getStatusColor = (status: SubAgentExecution['status']) => {
    switch (status) {
      case 'pending':
        return 'text-gray-500';
      case 'running':
        return 'text-blue-500';
      case 'completed':
        return 'text-green-500';
      case 'failed':
        return 'text-red-500';
    }
  };

  const getStatusIcon = (status: SubAgentExecution['status']) => {
    switch (status) {
      case 'pending':
        return <Brain className="w-4 h-4" />;
      case 'running':
        return <Zap className="w-4 h-4 animate-pulse" />;
      case 'completed':
        return <Cpu className="w-4 h-4" />;
      case 'failed':
        return <Cpu className="w-4 h-4" />;
    }
  };

  const getStatusBadge = (status: SubAgentExecution['status']) => {
    const labels: Record<SubAgentExecution['status'], string> = {
      pending: '等待中',
      running: '思考中',
      completed: '完成',
      failed: '失败',
    };

    const colors: Record<SubAgentExecution['status'], string> = {
      pending: 'bg-gray-500',
      running: 'bg-blue-500',
      completed: 'bg-green-500',
      failed: 'bg-red-500',
    };

    return (
      <Badge className={`${colors[status]} text-white text-xs`}>
        {labels[status]}
      </Badge>
    );
  };

  const formatDuration = (execution: SubAgentExecution) => {
    if (!execution.endTime) return null;
    const duration = execution.endTime.getTime() - execution.startTime.getTime();
    return `${Math.round(duration / 1000)}s`;
  };

  return (
    <div className="space-y-2">
      <div className="text-sm font-semibold text-muted-foreground flex items-center gap-2">
        <Brain className="w-4 h-4" />
        思考过程
      </div>

      <div className="space-y-2">
        {displayExecutions.map((execution, index) => (
          <Card key={execution.id} className="overflow-hidden">
            <CardContent className="p-3">
              <div className="flex items-start gap-3">
                {/* Step indicator */}
                <div className="flex flex-col items-center">
                  <div
                    className={`w-8 h-8 rounded-full flex items-center justify-center ${getStatusColor(
                      execution.status
                    )}`}
                  >
                    {getStatusIcon(execution.status)}
                  </div>
                  {index < displayExecutions.length - 1 && (
                    <div className="w-0.5 h-6 bg-border mt-2" />
                  )}
                </div>

                {/* Content */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap mb-1">
                    <span className="font-medium text-sm">{execution.agentName}</span>
                    {getStatusBadge(execution.status)}
                    {formatDuration(execution) && (
                      <span className="text-xs text-muted-foreground">
                        {formatDuration(execution)}
                      </span>
                    )}
                  </div>

                  {/* Input */}
                  {execution.input && (
                    <div className="text-xs text-muted-foreground mt-2">
                      <ChevronRight className="w-3 h-3 inline mr-1" />
                      {execution.input.length > 100
                        ? `${execution.input.slice(0, 100)}...`
                        : execution.input}
                    </div>
                  )}

                  {/* Output preview */}
                  {execution.output && execution.status === 'completed' && (
                    <div className="mt-2 p-2 bg-muted rounded text-xs">
                      {execution.output.length > 150
                        ? `${execution.output.slice(0, 150)}...`
                        : execution.output}
                    </div>
                  )}

                  {/* Error */}
                  {execution.error && (
                    <div className="mt-2 p-2 bg-red-500/10 text-red-500 rounded text-xs">
                      {execution.error}
                    </div>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}
